package com.wangsir.servlet;

import com.wangsir.entity.Admin;
import com.wangsir.entity.Student;
import com.wangsir.service.AdminService;
import com.wangsir.service.StudentService;
import com.wangsir.util.ApiResult;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    StudentService studentService = new StudentService();
    AdminService adminService = new AdminService();
    //登陆的时候使用post方法登陆的，所以不写get方法
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String userType = req.getParameter("userType");
        String captcha = req.getParameter("captcha");
        Object sessionCaptcha = req.getSession().getAttribute("captcha");
        //验证码输入错误直接进行return
        if(sessionCaptcha == null || !captcha.equalsIgnoreCase(sessionCaptcha.toString())){
            resp.getWriter().write(ApiResult.json(false,"验证码输入错误！"));
            return;
        }
        //判断角色是管理员还是学生
        if("admin".equals(userType)){
            //username在数据库中是主键
            Admin admin = adminService.getByUsername(username);
            //没有从数据库中查到该用户，就会返回空值
            if(admin == null){
                resp.getWriter().println(ApiResult.json(false,"用户不存在！"));
                return;
            }
            //反之查到该管理员
            if(admin.getPassword().equals(password)){
                req.getSession().setAttribute("user",admin);
                req.getSession().setAttribute("role","admin");
                resp.getWriter().println(ApiResult.json(true,"登录成功！"));
                return;
            }else{
                resp.getWriter().println(ApiResult.json(false,"密码错误！"));
                return;
            }
        }else{
            Student student = studentService.getStudentBySno(username);
            if(student == null){
                //这边返回的是json格式的字符串，前端会接受这个字符串，并且将字符串解析为js对象
                resp.getWriter().println(ApiResult.json(false,"用户不存在！"));
                return;
            }
            if(student.getPassword().equals(password)){
                req.getSession().setAttribute("user",student);
                req.getSession().setAttribute("role","student");
                resp.getWriter().println(ApiResult.json(true,"登录成功！"));
                return;
            }else{
                resp.getWriter().println(ApiResult.json(false,"密码错误！"));
                return;
            }
        }
    }
}
